package com.like.shopmanager;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.client.android.Intents;
import com.like.dialog.ConfirmDialogFragment;
import com.like.entity.CommonResult;
import com.like.entity.EventWrapper;
import com.like.entity.LoginedUser;
import com.like.entity.PushAmount;
import com.like.likeutils.network.RetrofitCallback;
import com.like.likeutils.network.RetrofitUtil;
import com.like.network.AmountService;
import com.like.receivers.PushMessageReceiver;
import com.like.widget.MoneyInputFilter;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.activity_recharge)
public class RechargeActivity extends BaseActivity implements Validator.ValidationListener {

    public static final int REQUEST_FROM_PUSH = 100;
    public static final int REQUEST_SCAN = 101;
    public static final String TAG_CONFIRM = "confirm_recharge";

    @ViewInject(R.id.money)
    @NotEmpty(message = "请输入充值金额")
    @Order(0)
    private EditText mMoney;
    @ViewInject(R.id.card_no)
    private TextView mTxtCardNo;
    @ViewInject(R.id.recharge)
    private Button mRecharge;
    private String mCardNo;

    private AmountService mAmountService;
    private Validator mValidator;
    private boolean mIsPass = false;
    private LoginedUser mUser;
    private ConfirmDialogFragment mConfirmDialog;
    private PushAmount mAmount;
    private MoneyInputFilter mMoneyInputFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mConfirmDialog = new ConfirmDialogFragment();
        mMoneyInputFilter = new MoneyInputFilter();
        mMoney.setFilters(new InputFilter[]{mMoneyInputFilter});
        mAmountService = RetrofitUtil.getGsonService(AmountService.class);
        mValidator = new Validator(this);
        mValidator.setValidationListener(this);
        mUser = m.getLoginedUser();
        if (mUser == null) {
            Toast.makeText(m.mContext, "请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(m.mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        }
        if (getIntent() != null) {
            String cardNo = getIntent().getStringExtra("cardNo");
            if (!TextUtils.isEmpty(cardNo)) {
                mTxtCardNo.setText("会员号：" + cardNo);
                mCardNo = cardNo;
            }
        }
        if (mAmount != null) {
            mTxtCardNo.setText("会员号：" + mAmount.cardNo);
            mCardNo = mAmount.cardNo;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(sticky = true)
    public void onGetStickyEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, PushMessageReceiver.TAG_PUSH, false)) {
            PushAmount amount = (PushAmount) event.data;
            mAmount = amount;
            if (amount.opType == PushAmount.TYPE_DEBIT) {
                Intent intent = new Intent(m.mContext, DebitActivity.class);
                startActivity(intent);
                finish();
                return;
            }
            EventBus.getDefault().removeStickyEvent(event);
            handlePush(amount);
        }
    }

    @Subscribe
    public void onGetEvent(EventWrapper event) {
        if (event.isMatch(event, ConfirmDialogFragment.TAG_OK)) {
            mConfirmDialog.dismiss();
            if (mAmount.customerResult == PushAmount.RESULT_ACCEPT)
                finish();
            else
                mMoney.setText("");
        }
    }

    private void handlePush(PushAmount amount) {
        mTxtCardNo.setText("会员号：" + amount.cardNo);
        if (amount.customerResult == PushAmount.RESULT_ACCEPT) {
            mConfirmDialog.setMessage("用户 " + amount.cardNo + " 已同意充值，充值成功");
        } else if (amount.customerResult == PushAmount.RESULT_REJECT) {
            mConfirmDialog.setMessage("用户 " + amount.cardNo + " 拒绝充值，请重新输入");
            mRecharge.setEnabled(true);
            mMoney.setText("");
        }
        if (!mConfirmDialog.isAdded())
            mConfirmDialog.show(getFragmentManager(), TAG_CONFIRM);
    }

    @Event(R.id.scanner_container)
    private void scanClick(View v) {
        Intent intent = new Intent(m.mContext, ScanActivity.class);
        startActivityForResult(intent, REQUEST_SCAN);
        mRecharge.setEnabled(true);
    }

    @Event(R.id.recharge)
    private void rechargeClick(View v) {
        mValidator.validate();
        if (!mIsPass)
            return;
        String money = mMoney.getText().toString();
        if (TextUtils.isEmpty(mCardNo)) {
            Toast.makeText(m.mContext, "请扫描二维码获取会员号", Toast.LENGTH_SHORT).show();
            return;
        }
        m.showLoading(true);
        mRecharge.setEnabled(false);
        String clientId = JPushInterface.getRegistrationID(m.mContext);
        Call<CommonResult> call = mAmountService.recharge(mCardNo, mUser.brandid, money, clientId,
                mUser.storeid, mUser.storeName);
        call.enqueue(new RetrofitCallback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                m.showLoading(false);
                if (!response.isSuccessful())
                    return;
                CommonResult result = response.body();
                if (result.code == 1) {
                    Toast.makeText(RechargeActivity.this, result.msg + "，等待用户确认", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RechargeActivity.this, result.msg + "，充值失败", Toast.LENGTH_SHORT).show();
                    mRecharge.setEnabled(true);
                }
            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                m.showLoading(false);
                Toast.makeText(RechargeActivity.this, "充值失败", Toast.LENGTH_SHORT).show();
                mRecharge.setEnabled(true);
            }
        });
    }

    @Event(R.id.back)
    private void backClick(View v) {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        if (requestCode != REQUEST_SCAN)
            return;
        String result = data.getStringExtra(Intents.Scan.RESULT);
        if (TextUtils.isEmpty(result)) {
            Toast.makeText(m.mContext, "扫描结果为空", Toast.LENGTH_SHORT).show();
            return;
        }
        mTxtCardNo.setText("会员号：" + result);
        mCardNo = result;
    }

    @Override
    public void onValidationSucceeded() {
        mIsPass = true;
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        mIsPass = false;
        String msg = errors.get(0).getCollatedErrorMessage(m.mContext);
        Toast.makeText(RechargeActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
